// import http from '../../g-server';

/**
 * 产品分类状态枚举
 */
export enum CategoryStatus {
  Disabled = 0,  // 禁用
  Enabled = 1,   // 启用
}

/**
 * 产品分类信息接口
 */
export interface Category {
  id: string | number;
  name: string;
  code: string;
  parentId?: string | number;
  level?: number;
  description?: string;
  status?: CategoryStatus;
  sortOrder?: number;
  createTime?: string;
  updateTime?: string;
}

/**
 * 产品分类列表查询参数
 */
export interface CategoryListParams {
  page: number;
  pageSize: number;
  keyword?: string;
  parentId?: string | number;
  status?: CategoryStatus;
  startDate?: string;
  endDate?: string;
}

/**
 * 产品分类列表查询结果
 */
export interface CategoryListResult {
  list: Category[];
  total: number;
}

/**
 * 产品分类服务类
 */
class CategoryService {
  /**
   * 获取产品分类列表
   * @param params 查询参数
   */
  async getCategoryList(params: CategoryListParams): Promise<CategoryListResult> {
    // 实际项目中应该调用API
    // const response = await http.get('/category/list', { params });
    // return response.data;
    
    // 模拟数据
    const mockCategories: Category[] = [];
    
    // 生成一级分类
    for (let i = 1; i <= 10; i++) {
      mockCategories.push({
        id: i,
        name: `一级分类 ${i}`,
        code: `C${i.toString().padStart(6, '0')}`,
        level: 1,
        parentId: 0,
        description: `这是一级分类 ${i} 的详细描述`,
        status: i % 5 === 0 ? CategoryStatus.Disabled : CategoryStatus.Enabled,
        sortOrder: i,
        createTime: new Date(Date.now() - i * 86400000).toISOString().split('T')[0],
        updateTime: new Date(Date.now() - i * 43200000).toISOString().split('T')[0],
      });
      
      // 为每个一级分类生成二级分类
      for (let j = 1; j <= 5; j++) {
        const subId = i * 100 + j;
        mockCategories.push({
          id: subId,
          name: `二级分类 ${subId}`,
          code: `C${subId.toString().padStart(6, '0')}`,
          level: 2,
          parentId: i,
          description: `这是二级分类 ${subId} 的详细描述`,
          status: subId % 7 === 0 ? CategoryStatus.Disabled : CategoryStatus.Enabled,
          sortOrder: j,
          createTime: new Date(Date.now() - subId * 86400000).toISOString().split('T')[0],
          updateTime: new Date(Date.now() - subId * 43200000).toISOString().split('T')[0],
        });
      }
    }
    
    // 根据关键字过滤
    let filteredCategories = mockCategories;
    if (params.keyword) {
      const keyword = params.keyword.toLowerCase();
      filteredCategories = mockCategories.filter(
        category => 
          category.name.toLowerCase().includes(keyword) || 
          category.code.toLowerCase().includes(keyword)
      );
    }
    
    // 根据父级ID过滤
    if (params.parentId !== undefined) {
      filteredCategories = filteredCategories.filter(category => category.parentId === params.parentId);
    }
    
    // 根据状态过滤
    if (params.status !== undefined) {
      filteredCategories = filteredCategories.filter(category => category.status === params.status);
    }
    
    // 根据创建时间范围过滤
    if (params.startDate) {
      const startDate = new Date(params.startDate).getTime();
      filteredCategories = filteredCategories.filter(category => {
        if (!category.createTime) return false;
        return new Date(category.createTime).getTime() >= startDate;
      });
    }
    
    if (params.endDate) {
      const endDate = new Date(params.endDate).getTime();
      filteredCategories = filteredCategories.filter(category => {
        if (!category.createTime) return false;
        return new Date(category.createTime).getTime() <= endDate;
      });
    }
    
    // 计算分页
    const total = filteredCategories.length;
    const start = (params.page - 1) * params.pageSize;
    const end = start + params.pageSize;
    const list = filteredCategories.slice(start, end);
    
    // 模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 500));
    
    return {
      list,
      total,
    };
  }

  /**
   * 获取产品分类详情
   * @param id 分类ID
   */
  async getCategoryDetail(id: string | number): Promise<Category> {
    // 实际项目中应该调用API
    // const response = await http.get(`/category/${id}`);
    // return response.data;
    
    // 模拟数据
    await new Promise(resolve => setTimeout(resolve, 300));
    
    return {
      id,
      name: `分类 ${id}`,
      code: `C${Number(id).toString().padStart(6, '0')}`,
      level: Number(id) > 100 ? 2 : 1,
      parentId: Number(id) > 100 ? Math.floor(Number(id) / 100) : 0,
      description: '这是一个示例分类的详细描述',
      status: CategoryStatus.Enabled,
      sortOrder: 1,
      createTime: '2023-01-01',
      updateTime: '2023-01-15',
    };
  }

  /**
   * 创建产品分类
   * @param category 分类信息
   */
  async createCategory(category: Omit<Category, 'id'>): Promise<Category> {
    // 实际项目中应该调用API
    // const response = await http.post('/category', category);
    // return response.data;
    
    // 模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 500));
    
    return {
      id: Math.floor(Math.random() * 1000) + 100,
      ...category,
      createTime: new Date().toISOString().split('T')[0],
      updateTime: new Date().toISOString().split('T')[0],
    };
  }

  /**
   * 更新产品分类
   * @param category 分类信息
   */
  async updateCategory(category: Category): Promise<Category> {
    // 实际项目中应该调用API
    // const response = await http.put(`/category/${category.id}`, category);
    // return response.data;
    
    // 模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 500));
    
    return {
      ...category,
      updateTime: new Date().toISOString().split('T')[0],
    };
  }

  /**
   * 删除产品分类
   * @param id 分类ID
   */
  async deleteCategory(id: string | number): Promise<void> {
    // 实际项目中应该调用API
    // await http.delete(`/category/${id}`);
    
    // 模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 300));
  }

  /**
   * 获取所有分类（用于下拉选择）
   */
  async getAllCategories(): Promise<Category[]> {
    // 实际项目中应该调用API
    // const response = await http.get('/category/all');
    // return response.data;
    
    // 模拟数据
    const mockCategories: Category[] = [];
    
    // 生成一级分类
    for (let i = 1; i <= 10; i++) {
      mockCategories.push({
        id: i,
        name: `一级分类 ${i}`,
        code: `C${i.toString().padStart(6, '0')}`,
        level: 1,
        parentId: 0,
      });
      
      // 为每个一级分类生成二级分类
      for (let j = 1; j <= 5; j++) {
        const subId = i * 100 + j;
        mockCategories.push({
          id: subId,
          name: `二级分类 ${subId}`,
          code: `C${subId.toString().padStart(6, '0')}`,
          level: 2,
          parentId: i,
        });
      }
    }
    
    // 模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 300));
    
    return mockCategories;
  }
}

// 导出分类服务实例
export const categoryService = new CategoryService(); 